# UpgradeManager.gd
extends Node

# --- Resource Preloading ---
# You MUST create these .tres files in the editor first.
# Example structure, replace with your actual file paths.
const PLAYER_UPGRADES_PATH = "res://resources/upgrades/player/"
const WEAPON_UPGRADES_PATH = "res://resources/upgrades/weapons/"

var available_player_upgrades: Array[Resource] = []
var available_weapon_upgrades: Array[Resource] = []
# Could further categorize weapon upgrades by weapon type

var current_upgrade_options: Array[Resource] = []

func _ready():
	load_upgrades_from_directory(PLAYER_UPGRADES_PATH, available_player_upgrades)
	load_upgrades_from_directory(WEAPON_UPGRADES_PATH, available_weapon_upgrades)
	SignalBus.player_level_up.connect(trigger_level_up_options)
	print("UpgradeManager Ready. Loaded %d player, %d weapon upgrades." % [available_player_upgrades.size(), available_weapon_upgrades.size()])


func load_upgrades_from_directory(path: String, target_array: Array):
	var dir = DirAccess.open(path)
	if dir:
		dir.list_dir_begin()
		var file_name = dir.get_next()
		while file_name != "":
			if not dir.current_is_dir() and file_name.ends_with(".tres"):
				var resource = load(path.path_join(file_name))
				if resource:
					target_array.append(resource)
					# print("Loaded upgrade: ", file_name)
				else:
					printerr("Failed to load upgrade resource: ", path.path_join(file_name))
			file_name = dir.get_next()
	else:
		printerr("Could not open upgrade directory: ", path)


func trigger_level_up_options(_new_level: int):
	if GameManager.is_game_over: return

	print("Generating level up options...")
	current_upgrade_options = generate_random_options(3)

	if current_upgrade_options.is_empty():
		printerr("No upgrade options generated!")
		# Potentially grant gold/xp or handle this case gracefully
		return

	# Pause game via GameManager BEFORE showing UI might be better
	GameManager.pause_game()
	SignalBus.emit_signal("show_upgrade_screen", current_upgrade_options)


func generate_random_options(count: int) -> Array[Resource]:
	var options: Array[Resource] = []
	var possible_upgrades: Array[Resource] = []

	# Simple combination of all upgrades for now
	# TODO: Filter based on player's current weapons, stats, rarity etc.
	possible_upgrades.append_array(available_player_upgrades)
	possible_upgrades.append_array(available_weapon_upgrades) # TODO: Filter by owned weapons

	if possible_upgrades.size() <= count:
		# Not enough unique upgrades, return what we have (shuffled)
		possible_upgrades.shuffle()
		return possible_upgrades
	else:
		# Select unique random upgrades
		possible_upgrades.shuffle()
		for i in range(count):
			options.append(possible_upgrades[i])

	return options


func apply_upgrade(chosen_upgrade: Resource):
	print("Applying chosen upgrade: ", chosen_upgrade.resource_path if chosen_upgrade else "None")
	if not chosen_upgrade:
		printerr("Chosen upgrade is null!")
		GameManager.resume_game() # Ensure game resumes even if upgrade fails
		return

	# Emit a signal that the Player or specific Weapon system listens for
	SignalBus.emit_signal("upgrade_chosen", chosen_upgrade)

	# Resume game after applying (might be delayed slightly by UI fade out)
	GameManager.resume_game()


# --- Resource Script Definitions ---
# Place these resource scripts in scripts/resources/

# **scripts/resources/PlayerStatUpgrade.gd**
# class_name PlayerStatUpgrade
# extends Resource
#
# @export var stat_name: String = "" # e.g., "max_health", "move_speed", "pickup_range", "health_regen", "armor", "crit_chance", "xp_gain"
# @export var value_change: float = 0.0 # Can be absolute or percentage based on stat_name logic
# @export_multiline var description: String = ""
# @export var rarity: int = 1 # Higher = rarer (or use an enum)
# @export var icon: Texture2D = null


# **scripts/resources/WeaponUpgrade.gd**
# class_name WeaponUpgrade
# extends Resource
#
# @export var weapon_id: String = "" # Identifier for the weapon this applies to (e.g., "knife", "fire_staff")
# @export var upgrade_type: String = "" # e.g., "damage", "speed", "range", "special", "quantity"
# @export var value_change: float = 0.0
# @export_multiline var description: String = ""
# @export var rarity: int = 1
# @export var icon: Texture2D = null
# @export var is_new_weapon: bool = false # If true, this grants the weapon itself


# **scripts/resources/EnemyData.gd**
# class_name EnemyData
# extends Resource
#
# @export var enemy_id: String = "base_enemy"
# @export var health: float = 10.0
# @export var speed: float = 50.0
# @export var damage: float = 5.0
# @export var experience_yield: int = 1
# @export var attack_cooldown: float = 1.5
# @export var prefab: PackedScene = null # Link the enemy's .tscn file here
# @export var scale_with_time: bool = true # Whether health/damage increase over time


# **scripts/resources/WeaponData.gd**
# class_name WeaponData
# extends Resource
#
# @export var weapon_id: String = "base_weapon"
# @export var base_damage: float = 5.0
# @export var base_cooldown: float = 1.0
# @export var base_range: float = 300.0 # Or search range
# @export var prefab: PackedScene = null # Link the weapon's .tscn or projectile .tscn